package com.zerui.manager.app.accessauthorization.executer;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.alibaba.cola.exception.BizException;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zerui.cola.dto.Response;
import com.zerui.manager.accessauthorization.AccessAuth;
import com.zerui.manager.accessauthorization.domainservice.AccessAuthRepository;
import com.zerui.manager.web.cmd.AccessAuthAddCmd;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @Author wh
 * @create_time 2023-08-23 10:21
 */
@Component
@CatchAndLog
public class AccessAuthAddCmdExe {

	@Resource
	private AccessAuthRepository accessAuthRepository;

	public Response execute(AccessAuthAddCmd accessAuthAddCmd) {

		checkTime(accessAuthAddCmd);

		return accessAuthRepository.add(AccessAuth
				.builder()
					.name(accessAuthAddCmd.getName())
					.dateType(accessAuthAddCmd.getDateType())
					.endDate(accessAuthAddCmd.getEndDate())
					.remark(accessAuthAddCmd.getRemark())
					.endTime(accessAuthAddCmd.getEndTime())
					.createTime(LocalDateTime.now())
					.startDate(accessAuthAddCmd.getStartDate())
					.timeType(accessAuthAddCmd.getTimeType())
					.startTime(accessAuthAddCmd.getStartTime())
				.build()
		);
	}

	private static void checkTime(AccessAuthAddCmd accessAuthAddCmd) {
		if(accessAuthAddCmd.getDateType()>0){
			if(ObjectUtils.isEmpty(accessAuthAddCmd.getStartDate()) ||
					ObjectUtils.isEmpty(accessAuthAddCmd.getEndDate())
			){
				throw new BizException("开始日期或者结束日期不能为空");
			}

			if(accessAuthAddCmd.getStartDate().isAfter(accessAuthAddCmd.getEndDate())){
				throw new BizException("日期开始必须在结束之前");
			}
		}

		if(accessAuthAddCmd.getTimeType()>0){
			if(
					ObjectUtils.isEmpty(accessAuthAddCmd.getStartTime()) ||
					ObjectUtils.isEmpty(accessAuthAddCmd.getEndTime())
			){
				throw new BizException("开始时间或者结束时间不能为空");
			}

			if(accessAuthAddCmd.getStartTime().isAfter(accessAuthAddCmd.getEndTime())){
				throw new BizException("开始时间必须在结束之前");
			}
		}
	}
}
